<template>
  <doc-alert title="员工体系" url="https://doc.iocoder.cn/user-center/" />
  <doc-alert title="三方登陆" url="https://doc.iocoder.cn/social-user/" />
  <doc-alert title="Excel 导入导出" url="https://doc.iocoder.cn/excel-import-and-export/" />

  <el-row :gutter="10">
    <!-- 左侧部门树 -->
    <el-col :span="isHideTree ? 0 : 4" :xs="24">
      <ContentWrap class="h-1/1 !mb-0px">
        <DeptTree @node-click="handleDeptNodeClick" @hide-tree="setHideTree" />
      </ContentWrap>
    </el-col>
    <el-col :span="isHideTree ? 24 : 20" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="登录账号" prop="username">
                <el-input
                  v-model="queryParams.username"
                  placeholder="请输入登录账号"
                  clearable
                  @keyup.enter="handleQuery"
                  class="!w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="员工姓名" prop="nickname">
                <el-input
                  v-model="queryParams.nickname"
                  clearable
                  placeholder="请输入员工姓名"
                  @keyup.enter="handleQuery"
                  class="!w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="归属门店" prop="tenantIds">
                <el-select
                  v-model="queryParams.tenantIds"
                  placeholder="请选择归属门店"
                  clearable
                  multiple
                >
                  <el-option
                    v-for="dict in tenantList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="所属部门" prop="deptId">
                <el-tree-select
                  v-model="queryParams.deptId"
                  :data="deptList"
                  :props="defaultProps"
                  check-strictly
                  class="!w-full"
                  clearable
                  node-key="id"
                  placeholder="请选择所属部门"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="员工岗位" prop="postId">
                <el-select
                  v-model="queryParams.postId"
                  placeholder="请选择归属门店"
                  clearable
                  multiple
                >
                  <el-option
                    v-for="dict in postOptions"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="手机号码" prop="mobile">
                <el-input
                  v-model="queryParams.mobile"
                  placeholder="请输入手机号码"
                  clearable
                  @keyup.enter="handleQuery"
                  class="!w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="员工状态" prop="employeeStatus">
                <el-select v-model="queryParams.employeeStatus" placeholder="员工状态" clearable>
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.EMPLOYEE_STATUS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="账号状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="账号状态" clearable>
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="创建时间" prop="createTime">
                <el-date-picker
                  v-model="queryParams.createTime"
                  :disabled-date="disabledDate"
                  :shortcuts="defaultShortcuts"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
                <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
                <el-button
                  type="primary"
                  plain
                  @click="openForm('create')"
                  v-hasPermi="['system:user:create']"
                >
                  <Icon icon="ep:plus" /> 新增
                </el-button>
                <el-button
                  type="warning"
                  plain
                  @click="handleImport"
                  v-hasPermi="['system:user:import']"
                >
                  <Icon icon="ep:upload" /> 导入
                </el-button>
                <el-button
                  type="success"
                  plain
                  @click="handleExport"
                  :loading="exportLoading"
                  v-hasPermi="['system:user:export']"
                >
                  <Icon icon="ep:download" />导出
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </ContentWrap>
      <ContentWrap class="!mb-0px">
        <PureTableBar title="" :columns="columns" @refresh="handleQuery">
          <template #default="{ size, dynamicColumns }">
            <pure-table
              ref="tableRef"
              row-key="id"
              align-whole="center"
              :loading="loading"
              :size="size"
              :data="list"
              :columns="dynamicColumns"
              :row-class-name="tableRowClassName"
            >
              <template #nickname="scope">
                <div class="flex">
                  <div>
                    <el-image
                      :preview-teleported="true"
                      :src="scope.row.avatar"
                      class="w-[48px]! h-[48px]! m-r-10px rounded-4px align-middle"
                    />
                  </div>

                  <el-text>{{ scope.row.nickname }}</el-text>
                </div>
              </template>
              <template #sex="scope">
                <dict-text :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex" />
              </template>
              <template #operation="scope">
                <div class="flex items-center justify-center">
                  <el-button
                    type="primary"
                    link
                    @click="openForm('update', scope.row.id)"
                    v-hasPermi="['system:user:update']"
                  >
                    <Icon icon="ep:edit" />修改
                  </el-button>
                  <el-dropdown
                    @command="(command) => handleCommand(command, scope.row)"
                    v-hasPermi="[
                      'system:user:delete',
                      'system:user:update-password',
                      'system:permission:assign-user-role'
                    ]"
                  >
                    <el-button type="primary" link><Icon icon="ep:d-arrow-right" /> 更多</el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <!-- <el-dropdown-item
                          command="handleDelete"
                          v-if="checkPermi(['system:user:delete'])"
                        >
                          <Icon icon="ep:delete" />删除
                        </el-dropdown-item> -->
                        <el-dropdown-item command="handleMakeQrcode">
                          <Icon icon="ep:delete" />生成二维码
                        </el-dropdown-item>
                        <el-dropdown-item command="handleFrozenTenant">
                          <Icon icon="ep:document" />{{
                            scope.row.status == 0 ? '冻结' : '解冻'
                          }}账户
                        </el-dropdown-item>
                        <el-dropdown-item command="handleSourceTenant">
                          <Icon icon="ep:document" />归属商户
                        </el-dropdown-item>
                        <el-dropdown-item command="handleRecord">
                          <Icon icon="ep:document" />调岗记录
                        </el-dropdown-item>
                        <el-dropdown-item
                          command="handleResetPwd"
                          v-if="checkPermi(['system:user:update-password'])"
                        >
                          <Icon icon="ep:key" />重置密码
                        </el-dropdown-item>
                        <el-dropdown-item
                          command="handleRole"
                          v-if="checkPermi(['system:permission:assign-user-role'])"
                        >
                          <Icon icon="ep:circle-check" />分配角色
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
              <template #empty>
                <Empty />
              </template>
            </pure-table>
            <Pagination
              v-model:limit="queryParams.pageSize"
              v-model:page="queryParams.pageNo"
              :total="total"
              @pagination="getList"
            />
          </template>
        </PureTableBar>
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 员工导入对话框 -->
  <UserImportForm ref="importFormRef" @success="getList" />
  <!-- 分配角色 -->
  <UserAssignRoleForm ref="assignRoleFormRef" @success="getList" />
  <!-- 归属商户 -->
  <UserSourceTenant ref="sourceTenantRef" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { checkPermi } from '@/utils/permission'
import download from '@/utils/download'
import * as UserApi from '@/api/system/user'
import UserImportForm from './UserImportForm.vue'
import UserAssignRoleForm from './UserAssignRoleForm.vue'
import UserSourceTenant from './UserSourceTenant.vue'
import DeptTree from './DeptTree.vue'
import { PureTableBar } from '@/components/RePureTableBar'
import { defaultShortcuts } from '@/utils/formatTime'
import { defaultProps, handleTree } from '@/utils/tree'

/**时间范围限制 */
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
const tableRef = ref()
import { useTable } from './utils/hook'
const { columns } = useTable()
defineOptions({ name: 'SystemUser' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  username: undefined,
  nickname: undefined,
  tenantIds: [],

  mobile: undefined,
  status: undefined,
  deptId: undefined,
  postId: undefined,
  employeeStatus: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const isHideTree = ref(false) //是否隐藏部门树
const setHideTree = (value) => {
  isHideTree.value = value
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  if (type == 'update') {
    push({ name: 'UserEdit', params: { id } })
    return
  }
  push({ name: 'UserAdd' })
}

/** 员工导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 导出按钮操作 */
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserApi.exportUser(queryParams)
    download.excel(data, '员工数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleFrozenTenant':
      handleFrozenTenant(row)
      break
    case 'handleMakeQrcode':
      handleMakeQrcode(row)
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleRole':
      handleRole(row)
      break
    case 'handleSourceTenant':
      handleSourceTenant(row)
      break
    default:
      break
  }
}
/** 表格状态 */

const tableRowClassName = ({ row, rowIndex }: { row: any; rowIndex: number }) => {
  if (row.status === 1) {
    return 'freeze-row'
  }
  return ''
}
/** 归属商户 */
const sourceTenantRef = ref()
const handleSourceTenant = (row: any) => {
  sourceTenantRef.value.open(row)
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()

    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
} /** 冻结按钮操作 */
const handleFrozenTenant = async (row: UserApi.UserVO) => {
  try {
    let content = `是否${row.status == 0 ? '冻结' : '解冻'}员工${row.nickname}`
    let params = {
      id: row.id,
      status: row.status == 0 ? 1 : 0
    }
    // 删除的二次确认
    await message.delConfirm(content)
    // 发起删除

    await UserApi.updateUserStatus(params.id, params.status)
    message.success('冻结成功')
    // 刷新列表
    await getList()
  } catch {}
}
const handleMakeQrcode = async (row: UserApi.UserVO) => {
  try {
    // 删除的二次确认
    // 发起删除
    // await UserApi.deleteUser(id)
    message.success('生成成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 重置密码 */
const handleResetPwd = async (row: UserApi.UserVO) => {
  try {
    // 重置的二次确认
    const result = await message.prompt(
      '请输入"' + row.username + '"的新密码',
      t('common.reminder')
    )
    const password = result.value
    // 发起重置
    await UserApi.resetUserPwd(row.id, password)
    message.success('修改成功，新密码是：' + password)
  } catch {}
}

/** 分配角色 */
const assignRoleFormRef = ref()
const handleRole = (row: UserApi.UserVO) => {
  assignRoleFormRef.value.open(row)
}
/** 门店精简列表 */
import * as TenantApi from '@/api/system/tenant'
const tenantList = ref<any[]>([])
const getTenantList = async () => {
  let params = {
    tenantType: 4
  }
  const data = await TenantApi.getChildTenantWithPostList(params)

  data.map((ele) => {
    tenantList.value.push({
      name: ele.name,
      id: ele.id
    })
  })
}

import * as DeptApi from '@/api/system/dept'
const deptList = ref<any>([])
import * as PostApi from '@/api/system/post'

const postOptions = ref<PostApi.PostVO[]>([]) // 岗位列表

/** 初始化 */
onMounted(async () => {
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 获得岗位列表
  postOptions.value = await PostApi.getSimplePostList()
  getTenantList()
  getList()
})
onActivated(async () => {
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 获得岗位列表
  postOptions.value = await PostApi.getSimplePostList()
  getTenantList()

  getList()
})
</script>
<style>
.el-table .freeze-row {
  --el-table-tr-bg-color: var(--el-table-row-hover-bg-color);
  cursor: not-allowed;
}
</style>
